from typing import Any, Text, Dict, List

from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher


# -*- coding: utf-8 -*-
import logging
import json
import datetime
from datetime import datetime
from typing import Any, Dict, List, Text, Optional

from rasa_sdk import Action, Tracker
from rasa_sdk.types import DomainDict
from rasa_sdk.forms import FormValidationAction
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.events import (
    SlotSet,
    UserUtteranceReverted,
    ConversationPaused,
    EventType,
)

from actions.api.qwenapi import qwen
from actions.api.txt2sql import sql
from actions.api.doctor import doctor

USER_INTENT_OUT_OF_SCOPE = "out_of_scope"

logger = logging.getLogger(__name__)
# logging.basicConfig(filename='myaction.log', level=logging.INFO)
logging.info('######## action log')
# sql = Text2Sql.sql
# doctor =  DoctorAPI()
logging.info('######## QwenAPI log')

def LlmAction(dispatcher: CollectingDispatcher,tracker):
    txt = tracker.latest_message.get("text")
    logger.info('###### LlmAction latest_message txt = '+ txt)
    cls = TxtClass(txt)
    if cls.find('rasa') != -1:
        # dispatcher.utter_message(template="utter_greet")
        return []
    if cls.find('sql') != -1:
        SqlAction(dispatcher,txt)
        return []
    if cls.find('doctor') != -1:
        DoctorAction(dispatcher,txt)
        return []
    # ret = qwen.predict(txt)
    logger.info('###### txt ='+ txt)
    ret = doctor.ragchat(txt)
    logger.info('###### ret =')
    logger.info(ret)
    dispatcher.utter_message(ret)

def TxtClass(txt):
    prompt = f'''
Some text is provided below. 
text：感冒,头疼,什么药
label：doctor
text：治疗,疾病,药品
label：doctor
text：[sql]
label：sql
text：统计,查询,删除,修改,增加
label：sql
text：10+10
label：other
label为doctor,sql,other.分类默认是sql。
text：{txt}
label：
请回答label是什么?
    '''
    # ret = qwen.predict(prompt)
    logger.info('###### TxtClass  ret =')
    if txt == 'Hi' or  txt == 'hi':
        ret = 'rasa'
    else:
        ret = 'sql'
    logger.info(ret)
    return ret

def SqlAction(dispatcher: CollectingDispatcher,txt):
    test_case = {
        'sql':[[txt, '']]
    }
    ret = sql.toSql(test_case)
    logger.info('###### ret =')
    logger.info(ret)
    dispatcher.utter_message(ret)

def DoctorAction(dispatcher: CollectingDispatcher,txt):
    ret = doctor.predict('robot_doctor',txt)
    logger.info('###### ret =')
    logger.info(ret)
    dispatcher.utter_message(ret)

class ActionDefaultFallback(Action):
    def name(self) -> Text:
        return "action_default_fallback"

    def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: DomainDict,
    ) -> List[EventType]:
        LlmAction(dispatcher,tracker)
        return [ConversationPaused(), UserUtteranceReverted()]



class ActionLeaveWorld(Action):

    def name(self) -> Text:
        return "action_leave"

    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        begin_time = tracker.get_slot("begin_time")
        duration = tracker.get_slot("duration")
        leave_type = tracker.get_slot("leave_type")
        print(f"请假参数信息，开始时间：{begin_time}, 时长：{duration}，类型：{leave_type}")
        dispatcher.utter_message(text=f"您从{begin_time}开始，为期{duration}天的{leave_type}申请已提交，请关注审批进度")
        return []
